package datasource

import (
	"fmt"
	"github.com/shirou/gopsutil/cpu"
	"github.com/shirou/gopsutil/disk"
	"github.com/shirou/gopsutil/mem"
	"runtime"
	"sync"
	"time"
)

type ConnectorCommon struct {
	ConditionCode string `json:"condition_code"`
	ConnectorId uint8 `json:"connector_id"`
	MessageType uint8 `json:"message_type"`
	TenantId uint32 `json:"tenant_id"`
	LocalIp string `json:"local_ip"`
	Version string `json:"version"`
	System string `json:"system"`
	Architecture string `json:"architecture"`
}

const (
	HttpPost = "POST"

	MsgStatus = 0 // 连接器状态数据
	MsgDelay = 1 // 连接器时延数据

	// 公共错误码
	HttpOk = 200
	HttpTokenReset = 210
	HttpMethodError = 405
	HttpTokenError = 403
	HttpSystemError = 500
)

var GBaseInfo ConnectorCommon
var onceBaseInfo sync.Once
var GStartTime int64

func GetCpuPercent() (float64, error) {
	percent, err := cpu.Percent(time.Second, false)
	return percent[0], err
}

func GetMemPercent() (float64, error) {
	v, err := mem.VirtualMemory()
	return v.UsedPercent, err
}

func GetDiskPercent(path string)  (float64, error) {
	usageStat, err := disk.Usage(path)
	return usageStat.UsedPercent, err
}

func GetBaseInfo() {
	onceBaseInfo.Do(func() {
		GBaseInfo = ConnectorCommon{}
		GBaseInfo.System = runtime.GOOS
		GBaseInfo.Architecture = runtime.GOARCH
		GBaseInfo.TenantId = 12
		GBaseInfo.ConnectorId = 0
		GBaseInfo.MessageType = 0
		GBaseInfo.LocalIp = "192.168.0.0"
		GBaseInfo.Version = "1.0.0.1"
		GBaseInfo.ConditionCode = fmt.Sprintf("%d-%d-%s",
			GBaseInfo.TenantId, GBaseInfo.ConnectorId, GBaseInfo.LocalIp)
		fmt.Println("public base info : ", GBaseInfo)
	})
}

func GetRunTime() (uint64, error) {
	now := time.Now().Unix()
	if now < GStartTime {
		GStartTime = now
		return 0, fmt.Errorf("now < start")
	}
	return uint64(now - GStartTime), nil
}